from rest_framework.utils import json
from .models import LinuxAccess, QadAccess, UriProgramMapping, ApiData
from .serializers import ApiDataSerializer, ApiLogsSerializer
from .applog import make_logs
from .qadclient2018 import qad_client_script2018
from .qadclienthfldvl import qad_client_script_hfldvl
from .qadclient import qad_client_script
from rest_framework.response import Response
from rest_framework import status


def request_json_write_file(request, in_path):
    request_json = request.data
    print(request_json)
    trace_id = "test_trace_id"
    print("datasetjson:", request_json)
    # print(type(request_json))
    for dataset in request_json:
        table_det = request_json[dataset]

        # print(table_det, type(table_det))
        trace_id = table_det['traceid']
        del request_json[dataset]['company_code']
        del request_json[dataset]['domain']
        del request_json[dataset]['dataid']
        del request_json[dataset]['traceid']
    # print(trace_id)

    jsobj = json.dumps(request_json, ensure_ascii=False)
    print(jsobj)
    print(in_path)
    with open(in_path + trace_id + '.json', 'w', encoding='utf-8') as json_file:
        json_file.write(jsobj)


def create_dat_file(company_code, domain, trace_id, in_path, uri):
    try:
        data = get_qad_access(company_code, domain)
        # print(data.get('userid') + ' ' + data.get('password'))
        program = get_api_program(company_code, uri)
        # print(program, program.get('qad_program_code'))
        with open(in_path + trace_id + '.dat', 'w') as dat_file:
            dat_file.write('"' + in_path + trace_id + '.json' + '" "'
                           + program.get('qad_program_code') + '" "'
                           + in_path
                           + trace_id
                           + '.out.log'
                           + '" ')
            dat_file.write('"' + data.get('userid') + '"' + ' ' +
                           '"' + data.get('password') + '"')
            dat_file.write('\n')
            dat_file.write('"' + domain + '"')
            dat_file.write('\n')
    except Exception as e:
        return False
    return True


def get_linux_access(company_code, server_code, uri):
    linux_access = LinuxAccess.objects.filter(company_code=company_code, server_code=server_code, uri=uri).values()[0]

    return linux_access


def get_qad_access(company_code, domain):
    qad_access = QadAccess.objects.filter(company_code=company_code, domain=domain).values()[0]

    return qad_access


def get_api_program(company_code, uri):
    print(company_code, uri)
    api_program = UriProgramMapping.objects.filter(company_code=company_code, uri=uri).values()[0]

    return api_program


def save_api_data(uri, data, status, data_id, company_code, company_name):
    check_data_id = ApiData.objects.filter(company_code=company_code, data_id=data_id)
    # print("check_data_id", check_data_id, check_data_id.exists())
    if not check_data_id.exists():
        api_data = {"company_code": company_code,
                    "company_name": company_name,
                    "uri": uri,
                    "json_data": data,
                    "data_id": data_id,
                    "status": status,
                    "user": 1
                    }

        serializer = ApiDataSerializer(data=api_data, many=False)
        # print(serializer)
        if serializer.is_valid():
            serializer.save()
            print("success save")
            return True
        print("save failed")
        return False
    return True


def save_logs(company_code, trace_id, data_id, uri, status, request_ip):
    log_data = {"company_code": company_code,
                "company_name": "test",
                "trace_id": trace_id,
                "data_id": data_id,
                "status": status,
                "uri": uri,
                "request_id": "WMS",
                "response_code": "200",
                "user": 1,
                "request_ip": request_ip}
    serializer = ApiLogsSerializer(data=log_data, many=False)
    # print(serializer)
    if serializer.is_valid():
        serializer.save()
        print("logs success save")
        return True
    if not serializer.is_valid():
        print("logs save failed")
        print(serializer.errors)
        return False


def create_qad_program(company_code, in_path, trace_id, uri):
    script_conf = get_api_program(company_code, uri)
    print(script_conf.get('script_path'), script_conf.get('script_program'), in_path, trace_id)
    with open(in_path + trace_id + '.p', 'w') as qad_program:
        qad_program.write('output to ' + in_path + trace_id + '.run.log.')
        qad_program.write('\n')
        qad_program.write('input from ' + in_path + trace_id + '.dat.')
        qad_program.write('\n')
        qad_program.write('run ' + script_conf.get('script_path') + script_conf.get('script_program') + '.')
        qad_program.write('\n')
        qad_program.write('input close.')
        qad_program.write('\n')
        qad_program.write('output close.')
    return True


def api_process(request, uri):
    for data in request.data:
        data_det = request.data[data]
        data_id = data_det.get('dataid')
        trace_id = data_det.get('traceid')
        company_code = data_det.get('company_code')
        domain = data_det.get('domain')
        linux_access = (get_linux_access(company_code, "MasterServer", uri))
        work_path = linux_access.get('work_path')
        make_logs("API: " + uri + " " + trace_id + " before write json...")
        request_json_write_file(request, work_path)
        make_logs("API: " + uri + " " + trace_id + " before save api data...")
        save_status = save_api_data(uri,
                                    request.data,
                                    "200",
                                    data_id,
                                    company_code,
                                    "海拉测试")
        make_logs("API: " + uri + " " + trace_id + " before write dat file...")
        create_dat_file(company_code, domain, trace_id, work_path, uri)
        make_logs("API: " + uri + " " + trace_id + " before write program file...")
        create_qad_program(company_code, work_path, trace_id, uri)
        make_logs("API: " + uri + " " + trace_id + " before execution client...")
        if company_code == 'HFLTEST':
            ret_data, ret_status = qad_client_script_hfldvl(work_path +
                                                            trace_id + '.p',
                                                            work_path, trace_id)
        else:
            ret_data, ret_status = qad_client_script2018(work_path +
                                                         trace_id + '.p',
                                                         work_path, trace_id)
        if save_status and ret_status:
            make_logs("API: " + uri + " " + trace_id + " before save logs client...")
            save_logs(company_code,
                      trace_id,
                      data_id,
                      uri,
                      str(ret_status),
                      "192.168.8.111")
            make_logs("API: " + uri + " " + trace_id + " all done ...")
            return True, ret_data
        # return Response('ee', status=status.HTTP_400_BAD_REQUEST)
        if not ret_status:
            make_logs("API: " + uri + " " + trace_id + " before save logs client...")
            save_logs(company_code,
                      trace_id,
                      data_id,
                      uri,
                      str(ret_status),
                      "192.168.8.111")
            make_logs("API: " + uri + " " + trace_id + " Error ...")
            return False, ret_data
